import {defineStore} from 'pinia'
import {login, getUserInfo, register, updateUserInfo} from '@/api/index.js'

export const useUserStore = defineStore('user', {
    state: () => ({
        user: {
            id: '',
            username: '',
            nickname: '',
            email: '',
            biography: '这人很懒，什么都没写',
            last_login: '',
            avatar_url: ''
        },
        token: localStorage.getItem('access') || null,
        isLogin: false,
        loading: false,
        error: null
    }),

    actions: {
        // 登录
        async userLogin(payload, remember = false) {
            this.loading = true
            this.error = null
            try {
                const res = await login(payload)

                // 1. 存储 token
                this.token = res.data.access
                sessionStorage.setItem('access', res.data.access)
                sessionStorage.setItem('refresh', res.data.refresh)
                if (remember) {
                    localStorage.setItem('access', res.data.access)
                    localStorage.setItem('refresh', res.data.refresh)
                }

                // 2. 设置登录状态
                this.isLogin = true

                // 3. 获取用户信息
                await this.fetchUserInfo()
            } catch (err) {
                this.error = err
                throw err // 让组件拿到异常显示
            } finally {
                this.loading = false
            }
        },
        // 注册
        async userRegister(payload) {
            this.loading = true
            this.error = null
            try {
                const res = await register(payload)  // 结果不必获取，反正都要重新登录
                return res.data
            } catch (err) {
                this.error = err
                throw err
            } finally {
                this.loading = false
            }
        },
        // 获取用户信息
        async fetchUserInfo() {
            try {
                const res = await getUserInfo()
                this.user = {...this.user, ...res.data}
                this.isLogin = true
            } catch (err) {
                this.isLogin = false
            }
        },
        // 更新用户信息
        async toUpdateUserInfo(data) {
            console.log(data)
            try {
                const res = await updateUserInfo(data)
                this.user = {...this.user, ...res.data}
                this.isLogin = true
            } catch (err) {
                throw Promise(err)
            }
        },
        // 退出登录
        logout() {
            this.token = null
            this.isLogin = false
            this.user = {
                id: '',
                username: '',
                nickname: '',
                email: '',
                biography: '这人很懒，什么都没写',
                last_login: '',
                avatar_url: ''
            }
            sessionStorage.removeItem('access')
            sessionStorage.removeItem('refresh')
            localStorage.removeItem('access')
            localStorage.removeItem('refresh')
        }
    }
})
